from pymongo import MongoClient
import gridfs
from bson import ObjectId
import gridfs
import os
from datetime import datetime 
from pymongo import MongoClient, DESCENDING
from bson.binary import Binary
from flask import jsonify
import io
import base64
import re

client = MongoClient('mongodb://localhost:27017/')

db = client['news']  # 替换为你想要的数据库名称
collection1 = db['newscoll']  # 替换为你想要的集合名称
collection2 = db['news_detail']  # 替换为你想要的集合名称

fs = gridfs.GridFS(db)

def get_news(code,newclass):
    if(code==1 and newclass=="新闻动态"):
        data_cursor = collection2.find({"class":newclass}).sort("_id", DESCENDING).limit(2)
    elif(code==1 and newclass != "新闻动态"):
        data_cursor = collection2.find({"class":newclass}).sort("_id", DESCENDING).limit(7)
    else:
        data_cursor = collection2.find({"class":newclass}).sort("_id", DESCENDING)
    data = [
    {
        'title': doc.get('title', 'No Title'),
        'date': (
            datetime.strptime(
                ' '.join(doc.get('date', 'No Date').split(' ')[:4]),
                '%a %b %d %Y'
            ).strftime('%Y-%m-%d')
        )
    }
    for doc in data_cursor
]
    data_cursor.close()
    return jsonify(data)

def get_data_with_files(title):
    news_items = list(collection2.find({"title": title}))
    # Format each news item and optionally include the image data
    formatted_recommend_items = [
        {
            'title': item['title'],
            'content': item['content'],
            'date': (
                    datetime.strptime(
                        ' '.join(item['date'].split(' ')[:4]),  # 只保留前三部分
                        '%a %b %d %Y'  # 匹配日期格式
                    ).strftime('%Y-%m-%d')  # 转换为 YYYY-MM-DD 格式
                ),
            'source': 'admin',
            'detailPath': f'https://example.com/news/{str(item["_id"])}',
            'image': (
                'data:image/jpeg;base64,' +
                base64.b64encode(fs.get(ObjectId(item['image_id'])).read()).decode('utf-8')
            ) if 'image_id' in item and item['image_id'] else None
        }
        for item in news_items
    ]

    # Reverse the list so that the latest news comes first

    return jsonify(formatted_recommend_items)

def insertnews(data):
    title = data.form.get('title')
    content = data.form.get('content')
    date = data.form.get('date')
    newclass = data.form.get('class')
    # 检查是否有文件在请求中
    if 'image' in data.files:
        file = data.files['image']
        
        if file:
            # 读取文件的二进制数据
            binary_data = file.read()
            # 创建 Binary 对象
            b = Binary(binary_data)
            # 创建 GridFS 文件记录
            gridfs_file = {
                '_id': ObjectId(),
                'filename': file.filename,
                'contentType': file.content_type,
                'uploadDate': datetime.utcnow()
            }
            
            # 将文件记录保存到 MongoDB
            # 传递二进制数据作为第一个参数，然后传递元数据
            new_id = str(fs.put(binary_data, **gridfs_file))
        else:
            new_id = None
    else:
        new_id = None

    # 创建会议数据记录
    meeting_data = {
        'title': title,
        'content': content,
        'date': date,
        'class':newclass,
        'image_id': new_id  # 保存 GridFS 文件的 _id
    }

    res=collection2.insert_one(meeting_data)
    
    return "00"